package com.xingkeduo.controller.provide;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.configuration.RedisListOpsService;
import com.xingkeduo.controller.base.InitController;
import com.xingkeduo.dao.TMarketingCouponBagMapper;
import com.xingkeduo.model.param.ActivityCombinationParam;
import com.xingkeduo.model.param.MarketingParam;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveSendTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveStatusEnum;
import com.xingkeduo.service.api.activity.PreferentialActivityService;
import com.xingkeduo.service.api.marketing.CardService;
import com.xingkeduo.service.api.marketing.CouponService;
import com.xingkeduo.service.api.marketing.ReceiveService;
import com.xingkeduo.service.api.marketing.StoreService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.RedisKeyEnum;
import com.xingkeduo.util.tool.ResponseMessage;

/**
 * 
 * @ClassName: ProvideController
 * @Description: feign服务提供
 * @author lixin
 * @date May 13, 2019 3:27:49 PM
 *
 */
@RestController
@RequestMapping(Constant.API_URL_PREFIX + "/provide")
public class ProvideController extends InitController {
	Logger logger =LoggerFactory.getLogger(ProvideController.class);

	@Autowired
	CouponService couponService;
	@Autowired
	CardService cardService;
	@Autowired
	StoreService storeService;
	@Autowired
	PreferentialActivityService preferentialActivityService;
	@Autowired
	ReceiveService receiveService;
	@Autowired
	TMarketingCouponBagMapper tMarketingCouponBagMapper;
	@Autowired
	RedisListOpsService redisListOpsService;

	/**
	 * 
	 * @Title: getUserCardList
	 * @Description: 获取用户领卡记录
	 * @param @param  marketingReceiveHistoryParam
	 * @param @return 设定文件
	 * @return ResponseMessage 返回类型
	 * @throws @author lixin
	 * @date Apr 30, 2019 10:44:18 AM
	 */
	@RequestMapping("/getUserCardList")
	public String getUserCardList(String userCardListParam) {
		MarketingReceiveHistoryParam marketingReceiveHistoryParam = JSONObject.parseObject(userCardListParam,
				MarketingReceiveHistoryParam.class);
		marketingReceiveHistoryParam.setMarketingType(MarketingTypeEnum.CARD.getCode());
		// 券类型
		if (MarketingTypeEnum.parseStatus(marketingReceiveHistoryParam.getMarketingType())
				.equals(MarketingTypeEnum.UNKNOWN)) {
			return ResponseMessage.error("优惠券，卡类型不合法", 500).toString();
		}
		// 券使用状态
		if (MarketingReceiveStatusEnum.parseStatus(marketingReceiveHistoryParam.getStatus())
				.equals(MarketingReceiveStatusEnum.UNKNOWN)) {
			return ResponseMessage.error("优惠券，卡使用状态不合法", 500).toString();
		}
		return cardService.queryCardByTemplateNoPage(marketingReceiveHistoryParam).toString();
	}

	/**
	 * 
	 * @Title: getUserCardDetail
	 * @Description: 查询卡详情
	 * @param @param  marketingReceiveHistoryId
	 * @param @param  request
	 * @param @return 设定文件
	 * @return ResponseMessage 返回类型
	 * @throws @author lixin
	 * @date May 2, 2019 3:04:17 PM
	 */
	@RequestMapping("/getUserCardDetail")
	public String getUserCardDetail(String userCardDetailParam) {
		MarketingReceiveHistoryParam marketingReceiveHistoryParam = JSONObject.parseObject(userCardDetailParam,
				MarketingReceiveHistoryParam.class);
		marketingReceiveHistoryParam.setMarketingType(MarketingTypeEnum.CARD.getCode());
		// 领取记录ID
		if (marketingReceiveHistoryParam.getId() == null) {
			return ResponseMessage.error("优惠券，卡记录ID不合法", 500).toString();
		}
		// 券类型
		if (MarketingTypeEnum.parseStatus(marketingReceiveHistoryParam.getMarketingType())
				.equals(MarketingTypeEnum.UNKNOWN)) {
			return ResponseMessage.error("优惠券，卡类型不合法", 500).toString();
		}
		return cardService.queryCardDetailByTemplate(marketingReceiveHistoryParam).toString();
	}

	/**
	 * 
	 * @Title: getUserCouponList
	 * @Description: 获取用户领券记录
	 * @param @param  marketingReceiveHistoryParam
	 * @param @return 设定文件
	 * @return ResponseMessage 返回类型
	 * @throws @author lixin
	 * @date Apr 30, 2019 10:44:18 AM
	 */
	@RequestMapping("/getUserCouponList")
	public String getUserCouponList(String userCouponListParam) {
		MarketingReceiveHistoryParam marketingReceiveHistoryParam = JSONObject.parseObject(userCouponListParam,
				MarketingReceiveHistoryParam.class);
		marketingReceiveHistoryParam.setMarketingType(MarketingTypeEnum.COUPON.getCode());
		// 券类型
		if (MarketingTypeEnum.parseStatus(marketingReceiveHistoryParam.getMarketingType())
				.equals(MarketingTypeEnum.UNKNOWN)) {
			return ResponseMessage.error("优惠券，卡类型不合法", 500).toString();
		}
		// 券使用状态
		if (MarketingReceiveStatusEnum.parseStatus(marketingReceiveHistoryParam.getStatus())
				.equals(MarketingReceiveStatusEnum.UNKNOWN)) {
			return ResponseMessage.error("优惠券，卡使用状态不合法", 500).toString();
		}
		return couponService.queryCouponByTemplateNoPage(marketingReceiveHistoryParam).toString();
	}

	/**
	 * 
	 * @Title: getUserCouponDetail
	 * @Description: 查询券详情
	 * @param @param  marketingReceiveHistoryId
	 * @param @param  request
	 * @param @return 设定文件
	 * @return ResponseMessage 返回类型
	 * @throws @author lixin
	 * @date May 2, 2019 3:04:17 PM
	 */
	@RequestMapping("/getUserCouponDetail")
	public String getUserCouponDetail(String userCouponDetailParam) {
		MarketingReceiveHistoryParam marketingReceiveHistoryParam = JSONObject.parseObject(userCouponDetailParam,
				MarketingReceiveHistoryParam.class);
		marketingReceiveHistoryParam.setMarketingType(MarketingTypeEnum.COUPON.getCode());
		// 领取记录ID
		if (marketingReceiveHistoryParam.getId() == null) {
			return ResponseMessage.error("优惠券，卡记录ID不合法", 500).toString();
		}
		// 券类型
		if (MarketingTypeEnum.parseStatus(marketingReceiveHistoryParam.getMarketingType())
				.equals(MarketingTypeEnum.UNKNOWN)) {
			return ResponseMessage.error("优惠券，卡类型不合法", 500).toString();
		}
		return couponService.queryCouponDetailByTemplate(marketingReceiveHistoryParam).toString();
	}

	@RequestMapping("/getUserActivity")
	public String getUserActivity(String activityCombinationParam) {
		ActivityCombinationParam param = JSONObject.parseObject(activityCombinationParam,
				ActivityCombinationParam.class);
		return preferentialActivityService.getUserActivity(param).toString();
	}

	@RequestMapping("/getUserCoupon")
	public String getUserCoupon(String activityCombinationParam) {
		ActivityCombinationParam param = JSONObject.parseObject(activityCombinationParam,
				ActivityCombinationParam.class);
		return preferentialActivityService.getUserCoupon(param).toString();
	}

	@RequestMapping("/getUserCard")
	public String getUserCard(String activityCombinationParam) {
		ActivityCombinationParam param = JSONObject.parseObject(activityCombinationParam,
				ActivityCombinationParam.class);
		return preferentialActivityService.getUserCard(param).toString();
	}

	@RequestMapping("/queryMarketing")
	public String queryMarketing(String marketingParam) {
		MarketingParam param = JSONObject.parseObject(marketingParam, MarketingParam.class);
		return receiveService.queryMarketingDetailById(param).toString();
	}
	
	@RequestMapping("/queryMarketingInfo")
	public String queryMarketingInfo(String marketingParam) {
		MarketingParam param = JSONObject.parseObject(marketingParam, MarketingParam.class);
		if(param.getId()==null) {
			return ResponseMessage.error("参数缺失", 500).toString();
		}
		if(param.getMarketingType()==null) {
			return ResponseMessage.error("参数缺失", 500).toString();
		}
		return receiveService.queryMarketingDetailNoCheckById(param).toString();
	}

	@RequestMapping("/bindBatchReceiveAccount")
	public ResponseMessage bindBatchReceiveAccount(Long userId, String marketingBatchRelease) {
		logger.info("bindBatchReceiveAccount_param,userId:{},marketingBatchRelease:{}.",userId,marketingBatchRelease);
		if (userId == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		if (StringUtils.isBlank(marketingBatchRelease)) {
			return ResponseMessage.error("券,卡信息为空", 500);
		}
		try {
			return receiveService.bindBatchReceiveAccount(userId, marketingBatchRelease);
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}
	}
	
	@RequestMapping("/bindReceiveAccount")
	public ResponseMessage bindReceiveAccount(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		if (marketingReceiveHistoryParam.getUserId() == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		if (marketingReceiveHistoryParam.getMarketingId() == null) {
			return ResponseMessage.error("券,卡信息为空", 500);
		}
		if (marketingReceiveHistoryParam.getMarketingType() == null) {
			return ResponseMessage.error("券,卡类型为空", 500);
		}
		if (MarketingTypeEnum.parseStatus(marketingReceiveHistoryParam.getMarketingType()) == MarketingTypeEnum.UNKNOWN) {
			return ResponseMessage.error("券,卡类型未知", 500);
		}
		boolean isExcep = true;
	    long EXPIRE_TIME = 30 * 1000;
	    String keyName = RedisKeyEnum.RECEIVE_CONCURRENT_USER_KEY.getKeyName(marketingReceiveHistoryParam.getMarketingType()+":"+marketingReceiveHistoryParam.getMarketingId()+":"+marketingReceiveHistoryParam.getUserId());
		long _time1 = System.currentTimeMillis();
		try {
			// 创建同步锁,防止任务阻塞重复执行
			boolean locked = redisListOpsService.locked(keyName, "LOCK",EXPIRE_TIME);
			if (!locked) {
				isExcep = false;
				logger.info("【扫码兑换】兑换中。。。。");
				return ResponseMessage.error("兑换中", 500);
			}
			marketingReceiveHistoryParam.setCreateBy(marketingReceiveHistoryParam.getUserId());
			if(marketingReceiveHistoryParam.getSendType()==null) {
				marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.SWEEP_CODE.getCode());
			}
			return receiveService.bindReceiveAccount(marketingReceiveHistoryParam);
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}finally {
			if(isExcep){
				redisListOpsService.unlock(keyName);
				long _time2 = System.currentTimeMillis();
				logger.info("【扫码兑换】解锁key： "+ keyName + "+ 耗时：" + (_time2 - _time1));
			}
		}
	}

	@RequestMapping("/bindBagReceiveAccount")
	public ResponseMessage bindBagReceiveAccount(Long userId, Long marketingBagId) {
		if (userId == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		if (marketingBagId == null) {
			return ResponseMessage.error("券包信息为空", 500);
		}
		boolean isExcep = true;
	    long EXPIRE_TIME = 30 * 1000;
	    String keyName = RedisKeyEnum.RECEIVE_CONCURRENT_USER_KEY.getKeyName(marketingBagId+":"+MarketingTypeEnum.COUPON_BAG.getCode()+":"+userId);
		long _time1 = System.currentTimeMillis();
		try {
			// 创建同步锁,防止任务阻塞重复执行
			boolean locked = redisListOpsService.locked(keyName, "LOCK",EXPIRE_TIME);
			if (!locked) {
				isExcep = false;
				logger.info("【扫码兑换】兑换中。。。。");
				return ResponseMessage.error("兑换中", 500);
			}
			MarketingReceiveHistoryParam marketingReceiveHistoryParam = new MarketingReceiveHistoryParam();
			marketingReceiveHistoryParam.setCreateBy(userId);
			marketingReceiveHistoryParam.setMarketingId(marketingBagId);
			marketingReceiveHistoryParam.setMarketingType(MarketingTypeEnum.COUPON_BAG.getCode());
			marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.SWEEP_CODE.getCode());
			return receiveService.bindBagReceiveAccount(marketingReceiveHistoryParam);
		} catch (Exception e) {
			logger.error("领取优惠包异常，e:{}",e);
			return ResponseMessage.error(e.getMessage(), 500);
		}finally {
			if(isExcep){
				redisListOpsService.unlock(keyName);
				long _time2 = System.currentTimeMillis();
				logger.info("【扫码兑换】解锁key： "+ keyName + "+ 耗时：" + (_time2 - _time1));
			}
		}
	}
	@RequestMapping("/bindCompensationReceiveAccount")
	public ResponseMessage bindCompensationReceiveAccount(Long userId) {
		if (userId == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		try {
			MarketingReceiveHistoryParam marketingReceiveHistoryParam = new MarketingReceiveHistoryParam();
			marketingReceiveHistoryParam.setCreateBy(userId);
			marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.OVERTIME.getCode());
			return receiveService.delayCompensateBindReceiveAccount(marketingReceiveHistoryParam);
			
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}
	}
	
	@RequestMapping("/bindReceiveAccountOfShareNewUser")
	public ResponseMessage bindReceiveAccountOfShareNewUser(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		if (marketingReceiveHistoryParam.getUserId() == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		boolean isExcep = true;
	    long EXPIRE_TIME = 30 * 1000;
	    String keyName = RedisKeyEnum.RECEIVE_CTOC_NEW_USER_KEY.getKeyName(marketingReceiveHistoryParam.getUserId()+"");
		long _time1 = System.currentTimeMillis();
		try {
			// 创建同步锁,防止任务阻塞重复执行
			boolean locked = redisListOpsService.locked(keyName, "LOCK",EXPIRE_TIME);
			if (!locked) {
				isExcep = false;
				logger.info("【C拉C兑换】兑换中。。。。");
				return ResponseMessage.error("兑换中", 500);
			}
			marketingReceiveHistoryParam.setCreateBy(marketingReceiveHistoryParam.getUserId());
			marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.INVITE.getCode());
			return receiveService.bindReceiveAccountOfShareNewUser(marketingReceiveHistoryParam);
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}finally {
			if(isExcep){
				redisListOpsService.unlock(keyName);
				long _time2 = System.currentTimeMillis();
				logger.info("【C拉C兑换】解锁key： "+ keyName + "+ 耗时：" + (_time2 - _time1));
			}
		}
	}
	
	@RequestMapping("/bindReceiveAccountOfShareOldUser")
	public ResponseMessage bindReceiveAccountOfShareOldUser(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		if (marketingReceiveHistoryParam.getUserId() == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		try {
			marketingReceiveHistoryParam.setCreateBy(marketingReceiveHistoryParam.getUserId());
			marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.INVITE.getCode());
			return receiveService.bindReceiveAccountOfShareOldUser(marketingReceiveHistoryParam);
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}
	}
	
	@RequestMapping("/bindBarberReceiveAccount")
	public ResponseMessage bindBarberReceiveAccount(Long userId,String hairType) {
		if (userId == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		if(StringUtils.isBlank(hairType)) {
			return ResponseMessage.error("缺少发型类型",500);
		}
		try {
			return receiveService.bindBarberReceiveAccount(userId,hairType);
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}
	}
	
	@RequestMapping("/checkUserHasBarberCoupon")
	public ResponseMessage checkUserHasBarberCoupon(Long userId,String hairType) {
		if (userId == null) {
			return ResponseMessage.error("用户ID缺失", 500);
		}
		if(StringUtils.isBlank(hairType)) {
			return ResponseMessage.error("缺少发型类型",500);
		}
		try {
			return receiveService.checkUserHasBarberCoupon(userId,hairType);
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}
	}
}
